import 'dart:async';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/login.dart';
import 'package:find_friend/pages/login&register/login_textfield.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:page_transition/page_transition.dart';

class MineSettingModPhonePage extends StatefulWidget {
  @override
  _MineSettingModPhonePageState createState() => _MineSettingModPhonePageState();
}

class _MineSettingModPhonePageState extends State<MineSettingModPhonePage> {

  final _phoneFoucs = FocusNode();
  final _codeFoucs = FocusNode();
  String code = "";
  String rightCode = "";
  bool _isverify_code = false;
  final TextEditingController _controller = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  int resentCode = 59;
  String resetString = "";
  Timer _timer;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    _codeController.dispose();
    _stopTimer();
    super.dispose();
  }


  _stopTimer() {
    if(_timer == null) return;
    _timer.cancel();
    _timer = null;
  }

  _beginTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(resentCode == 1) {
        _stopTimer();
        resentCode = 59;
        setState(() {
          resetString = "";
        });
      } else {
        resentCode -= 1;
        setState(() {
          resetString = "($resentCode)";
        });
      }
    });
  }

  void _sendSMS() {
    if(resentCode == 59 && _controller.text.length == 11) {
      Networktool.request(API.code, params: {"mobile":_controller.text, "event":"changemobile"},success:(data){
        print(data);
        if(data["data"] != null) {
          setState(() {
            rightCode = data["data"]["code"].toString();
          });
          _beginTimer();
        } else {
          AlertTool.showToast(data["msg"]);
        }
      }, fail: (data){
        AlertTool.showToast(data);
      });
    }
  }

  void _modPhone() {
    _codeFoucs.unfocus();
    _phoneFoucs.unfocus();
    if(_controller.text.length == 11) {
      Networktool.request(API.changemobile, params: {"mobile":_controller.text, "event":"changemobile","code":code},success:(data){
        AlertTool.showMsgDialog(context, msg:"您已更换手机号成功 请重新登录", callback: (){
          Navigator.of(context).pushAndRemoveUntil(
            PageTransition(
              type: PageTransitionType.fade,
              child: LoginScreen()
            ),
            (route) => false
          );
        });
      }, fail: (data){
        AlertTool.showToast(data);
      });
    } else {
      AlertTool.showToast("请输入手机号码");
    }
  }

  String _getCodeString(int index) {
    if(index < code.length) {
      return code[index];
    } else {
      return "";
    }
  }

  _initVerifyCode() {
    TextStyle style = TextStyle(color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold);
    return Stack(
      children: [
        Container(
          padding: const EdgeInsets.only(top: 20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("输入您的验证码叭～", style: instanceTextStyle(11, APP_font_grey),),
              SizedBox(height: 20,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(4, (index) => 
                Container(
                    width: 50,
                    height: 40,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(
                        color: _getCodeString(index) == "" ? Colors.black : (_isverify_code ? APP_main_color : APP_verify_error_color), width: 1.5)
                    ),
                    child: Text(_getCodeString(index), style: style),
                  )),
              ),
              Container(
                padding: const EdgeInsets.only(top: 20),
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  child: RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(text: "重新发送验证码",style: instanceTextStyle(11, APP_main_color, fontWeight: FontWeight.bold, decoration: TextDecoration.underline)),
                        TextSpan(text: resetString,style: instanceTextStyle(11, APP_main_color, fontWeight: FontWeight.bold)),
                      ]
                    ),
                  ),
                  onTap: _sendSMS,
                ),
              )
            ],
          ),
        ),
        Container(
          height: 130,
          child: TextField(
            controller: _codeController,
            showCursor: false,
            maxLength: 4,
            focusNode: _codeFoucs,
            style: TextStyle(color: Colors.transparent),
            keyboardType: TextInputType.number,
            inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
            decoration: InputDecoration(
              border: InputBorder.none,
              counterText: "",
            ),
            onChanged: (str){
              setState(() {
                code = str;
                if(str.length == 4) {
                  _isverify_code = str == rightCode;
                } else {
                  _isverify_code = true;
                }
              });
              if(_isverify_code == false && str.length == 4) {
                AlertTool.showToast("验证码有误");
              }
            },
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text("账号管理"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
        actions: [
          Offstage(
            offstage: rightCode != _codeController.text,
            child: FlatButton(
              child: Text("完成", style: instanceTextStyle(15, Colors.black, fontWeight: FontWeight.normal)),
              onPressed: _modPhone,
            ),
          )
        ],
      ),
      resizeToAvoidBottomPadding: false,
      body: SafeArea(
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){
            _phoneFoucs.unfocus();
            _codeFoucs.unfocus();
          },
          child: Padding(
            padding: const EdgeInsets.only(top: 20, left: 37.5, right: 37.5, bottom: 50),
            child: Column(
              children: [
                LoginTextField(
                  focusNode: _phoneFoucs,
                  controller: _controller,
                  maxlength: 11,
                  keybordType: TextInputType.number,
                  suffixTap: _sendSMS,
                  placeholder: "请输入原手机号",
                  suffixIconName: "assets/querensj.png",
                ),
                Offstage(
                  offstage: rightCode == "",
                  child: _initVerifyCode(),
                ),
                Spacer(),
                Offstage(
                  offstage: rightCode != _codeController.text,
                  child: GestureDetector(
                    onTap: _modPhone,
                    child: Container(
                      height: 40,
                      margin: const EdgeInsets.symmetric(horizontal: 15),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        border: Border.all(color:Colors.black, width: 1),
                        borderRadius: BorderRadius.circular(20)
                      ),
                      child: Text("确认",style: instanceTextStyle(18, Colors.black)),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}